<?php

namespace App\Repositories\Ca;

use App\Facade\AppContext;
use App\Models\BaseModel;
use App\Models\Ca\SmsTemplate;
use App\Repositories\BaseRepository;
use App\Utils\Output;
use App\Utils\QueryHelper;

class SmsTemplateRepository extends BaseRepository
{

    /**
     * 分页查询
     * @param array $params
     * @return Output
     */
    function adminPager(array $params)
    {
        extract($params);
        $query = $this->model->newQuery()->where('hospital_id', '=', AppContext::hospitalId());
        if (!empty($keyword)) {
            QueryHelper::like($query, 'name|code', $keyword);
        }
        $totalQuery = clone $query;
        $total = $totalQuery->count();
        $lis = $this->setParams($query, $params, ['id' => 'desc']);
        return Output::pager($lis, $total);
    }

    function lis()
    {
        $query = SmsTemplate::query()->where('hospital_id', '=', AppContext::hospitalId());
        $query->select('id', 'name');
        return $query->orderByDesc('id')->get();
    }

    /**
     * 获取对象详情
     * @param int $id
     * @return Output
     */
    function detail(int $id)
    {
        try {
            $entity = $this->model->find($id);
            if (!empty($entity)) {
                $params = $entity['params'];
                $data = [];
                $names = [];
                foreach ($params as $name => $value) {
                    $data[] = [
                        'name' => $name,
                        'value' => $value,
                    ];
                    $names[$name] = true;
                }
                $entity['names'] = count($names) ? json_encode($names) : '{}';
                $entity['params_data'] = json_encode($data);
                return Output::data($entity);
            }
            return Output::fail(__('common.tips.data_does_not_exist'));
        } catch (\Throwable $exception) {
            return Output::error($exception, __('common.tips.get_data_exception'));
        }
    }

    public function getParams()
    {
        $values = [];
        foreach (SmsTemplate::PARAMS as $value => $name) {
            $values[] = [
                'value' => $value,
                'label' => $name,
            ];
        }
        return $values;
    }

    function getModel(): BaseModel
    {
        return new SmsTemplate();
    }
}